<template>
  <div class="container">
    <h1>综合日报</h1>
    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="稀油注输联合站化学助剂使用台账" name="first">
        <div class="block">
          <el-card shadow="always">
            <span class="demonstration" style="font: bolder">日期:</span>
            <el-date-picker
              style="margin-left: 10px"
              v-model="paramDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <el-button type="primary" style="margin-left: 40px">查询</el-button>
          </el-card>
        </div>
        <el-card shadow="always" style="margin-top: 15px">
          <el-table :data="paginatedData" border stripe style="width: 100%">
            <el-table-column label="日期" width="120">
              <template slot-scope="scope">
                <i class="el-icon-time"></i>
                <span style="margin-left: 10px">{{ scope.row.date }}</span>
              </template>
            </el-table-column>
            <el-table-column label="处理液量(m³/d)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil001
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="正相破乳剂(kg/d)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil002"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil002')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="原油脱出污水量(m³/d)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil003
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="反相破乳剂(kg/d)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil004
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="反应器水量(m³/d)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil005
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="过滤器水量(m³/d)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil006
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="污泥进离心机量(t/d)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil007
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="注水量(m³/d)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil008
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="净水剂(L/d)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil009"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil009')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="絮凝剂(L/d)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil010"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil010')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="油区阻垢剂(L/d)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil011"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil011')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="阻垢剂(kg)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil012"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil012')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="杀菌剂(kg)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil013
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="助滤剂(收泥)(kg)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil014
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预处理剂(L/d)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil015"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil015')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="夏子街端点加药(正相)(kg)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil016"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil016')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="乌33端点加药(破乳剂kg)" width="150">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.thinOil017"
                  placeholder="请输入"
                  type="number"
                  size="small"
                  @input="handleInput(scope, 'thinOil017')"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="正相加药浓度(mg/L)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil018
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="反相加药浓度(mg/L)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil019
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="净水剂加药浓度(mg/L)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil020
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="絮凝剂加药浓度(mg/L)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil021
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="阻垢剂加药浓度(mg/L)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil022
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="杀菌剂加药浓度(mg/L)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil023
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="助滤剂(收泥)加药浓度(mg/L)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil024
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="预处理剂(mg/l)" width="150">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{
                  scope.row.thinOil025
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  plain
                  @click="handleEdit(scope.row)"
                >
                  保存
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <div class="block">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            :total="totalItems"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          ></el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
const calculationConfig = {
  thinOil001: "sum",
  thinOil002: "sum",
  thinOil003: "sum",
  thinOil004: "sum",
  thinOil005: "sum",
  thinOil006: "sum",
  thinOil007: "sum",
  thinOil008: "sum",
  thinOil009: "sum",
  thinOil010: "sum",
  thinOil011: "sum",
  thinOil012: "sum",
  thinOil013: "sum",
  thinOil014: "sum",
  thinOil015: "sum",
  thinOil016: "sum",
  thinOil017: "sum",
  thinOil018: "average",
  thinOil019: "average",
  thinOil020: "average",
  thinOil021: "average",
  thinOil022: "average",
  thinOil023: "average",
  thinOil024: "average",
  thinOil025: "average",
};
export default {
  data() {
    return {
      activeName: "first",
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据条数
      paramDate: ["2024-11-01", "2024-11-08"],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      tableData: [
        {
          date: "2016-05-02",
          id: "1",
          thinOil001: 4879,
          thinOil002: 1042,
          thinOil003: 2763,
          thinOil004: 0,
          thinOil005: 2321,
          thinOil006: 1784,
          thinOil007: 35,
          thinOil008: 2214,
          thinOil009: 10296,
          thinOil010: 9672,
          thinOil011: 0,
          thinOil012: 0,
          thinOil013: 0,
          thinOil014: 18,
          thinOil015: 0,
          thinOil016: 300,
          thinOil017: 0,
          thinOil018: 275,
          thinOil019: 0,
          thinOil020: 976,
          thinOil021: 5,
          thinOil022: 0,
          thinOil023: 0,
          thinOil024: 514,
          thinOil025: 0,
        },
      ],
      editedRows: new Set(), // 存储被编辑的行
    };
  },
  mounted() {},
  created() {
    // 调用方法，生成更多数据，例如添加10条
    this.addMoreData(56);
  },
  beforeDestroy() {},
  methods: {
    // 保存按钮点击事件
    handleEdit(row) {
      if (this.editedRows.has(row)) {
        // 调用后端 API 进行更新
        this.updateRecord(row)
          .then((response) => {
            this.$message.success("保存成功");
            this.editedRows.delete(row); // 保存后取消标记
          })
          .catch((error) => {
            this.$message.error("保存失败，请重试");
          });
      } else {
        this.$message.info("无更改无需保存");
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleInput(scope, field) {
      const value = scope.row[field];
      // 转换为数字，如果为空则设置为 NaN 或其他默认值
      scope.row[field] = value === "" ? null : Number(value);
      this.markAsEdited(scope.row);
    },
    // 标记被编辑的行
    markAsEdited(row) {
      this.editedRows.add(row);
    },
    // 更新记录的后端调用
    async updateRecord(row) {
      console.log("row", row);
      // 示例后端 API 请求
      const url = `/api/updateRecord`;
      const response = await axios.post(url, {
        date: row.date,
        mvc001: row.mvc001,
        mvc004: row.mvc004,
        mvc009: row.mvc009,
      });
      return response.data;
    },
    // 处理页码变更
    handlePageChange(page) {
      this.currentPage = page;
    },
    // 处理每页条数变更
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1; // 重置为第一页
    },
    addMoreData(repeatCount) {
      // 获取现有的数据作为模板
      const templateData = this.tableData[0];
      // 添加指定数量的重复数据
      for (let i = 1; i <= repeatCount; i++) {
        const newData = { ...templateData };
        // 更新日期或其他字段，以使每条数据项有所区别
        newData.date = `2016-05-${(i + 2).toString().padStart(2, "0")}`;
        newData.id = `${(i + 1).toString()}`;
        this.tableData.push(newData);
      }
      this.addSummaryRow(this.tableData, calculationConfig);
      this.calculateLastRowTableData();
    },
    calculateLastRowTableData() {
      // 获取表格的最后一行数据
      const lastRow = this.tableData[this.tableData.length - 1];
      if (lastRow) {
        lastRow.thinOil018 = +(
          ((lastRow.thinOil002 + lastRow.thinOil017 + lastRow.thinOil016) /
            lastRow.thinOil001) *
          1000
        ).toFixed(2);

        lastRow.thinOil019 = +(
          (lastRow.thinOil004 / lastRow.thinOil005) *
          1000
        ).toFixed(2);

        lastRow.thinOil020 = +(
          (lastRow.thinOil009 * 220) /
          lastRow.thinOil005
        ).toFixed(2);

        lastRow.thinOil021 = +(
          (lastRow.thinOil010 * 1.3) /
          lastRow.thinOil005
        ).toFixed(2);

        lastRow.thinOil022 = +(
          (lastRow.thinOil012 / lastRow.thinOil005) *
          1000
        ).toFixed(2);

        lastRow.thinOil023 = +(
          (lastRow.thinOil013 / lastRow.thinOil006) *
          1000
        ).toFixed(2);

        lastRow.thinOil024 = +(
          (lastRow.thinOil014 / lastRow.thinOil007) *
          1000
        ).toFixed(2);

        lastRow.thinOil025 = +(
          (lastRow.thinOil015 * 200) /
          lastRow.thinOil005
        ).toFixed(2);
      }
    },
    addSummaryRow(tableData, calculationConfig) {
      const summaryRow = { date: "全年合计" };
      // 动态获取需要计算的列名（排除 'date' 列）
      const columns = Object.keys(tableData[0]).filter(
        (column) => column !== "date"
      );
      // 遍历每列，按配置计算总和或平均值
      columns.forEach((column) => {
        const isSum = calculationConfig[column] === "sum";
        const total = tableData.reduce((sum, row) => {
          return sum + (row[column] || 0);
        }, 0);
        // 如果是求和，直接使用总和；如果是求平均，使用总和除以行数
        const result = isSum ? total : total / tableData.length;
        // 保留两位小数并转为数值
        summaryRow[column] = parseFloat(result.toFixed(2));
      });
      // 将合计行添加到表格数据
      tableData.push(summaryRow);
    },
  },
  computed: {
    // 总数据量
    totalItems() {
      return this.tableData.length;
    },
    // 分页后的数据
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    },
  },
};
</script>
<style scoped lang="scss">
.el-table_row .warning-row {
  background-color: red;
}

h1 {
  color: rgb(104, 224, 223);
  margin-bottom: 20px;
  margin-top: 20px;
  margin-left: 20px;
}
/* .container{
    height: 100vh;
  } */
.table-content {
  border: 3px solid rgb(30, 94, 158);
  width: 93%;
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 50px;
  /* margin:80px auto; */
  // height: 95vh;
  // overflow: auto;
}
.container {
  /* max-width: 600px;   */
  background-color: rgb(2, 16, 79);
  height: 100vh;
  overflow-x: auto; /* 设置横向滚动 */
  white-space: nowrap; /* 防止内容自动换行 */
}
.el-table {
  // overflow: auto;
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 20px;
  margin-bottom: 20px;

  /* height: 2000px; */
  border-color: #f0f0f0;
  border-width: 2px;

  /* background-color: red; */
}
</style>
